import React, { useState, useEffect } from 'react';
import { Typography, Breadcrumb, Descriptions, Card, Button, Tag, Steps, Divider, List, Row, Col, Image, Spin, message } from 'antd';
import { Link, useParams, useNavigate } from 'react-router-dom';
import { HomeOutlined, ShoppingOutlined, CreditCardOutlined, CheckCircleOutlined } from '@ant-design/icons';
import { getOrderById, Order, payOrder, cancelOrder } from '../services/order.service';
import { formatDate } from '../utils/time';

const { Title, Text } = Typography;
const { Step } = Steps;

const OrderDetailPage: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [paying, setPaying] = useState(false);
  const [cancelling, setCancelling] = useState(false);
  const [order, setOrder] = useState<Order | null>(null);

  useEffect(() => {
    if (id) {
      fetchOrderDetail(parseInt(id));
    }
  }, [id]);

  const fetchOrderDetail = async (orderId: number) => {
    try {
      setLoading(true);
      const data = await getOrderById(orderId);
      setOrder(data);
    } catch (error) {
      console.error('Failed to fetch order details:', error);
      message.error('获取订单详情失败');
    } finally {
      setLoading(false);
    }
  };

  const handlePay = async () => {
    if (!order) return;
    
    try {
      setPaying(true);
      await payOrder(order.id, 'alipay'); // 假设使用支付宝支付
      message.success('支付成功');
      fetchOrderDetail(order.id);
    } catch (error) {
      console.error('Failed to pay order:', error);
      message.error('支付失败，请稍后再试');
    } finally {
      setPaying(false);
    }
  };

  const handleCancel = async () => {
    if (!order) return;
    
    try {
      setCancelling(true);
      await cancelOrder(order.id);
      message.success('订单已取消');
      fetchOrderDetail(order.id);
    } catch (error) {
      console.error('Failed to cancel order:', error);
      message.error('取消订单失败');
    } finally {
      setCancelling(false);
    }
  };

  const getStatusTag = (status: string) => {
    switch (status) {
      case 'pending':
        return <Tag color="blue">待支付</Tag>;
      case 'paid':
        return <Tag color="green">已支付</Tag>;
      case 'cancelled':
        return <Tag color="red">已取消</Tag>;
      case 'completed':
        return <Tag color="purple">已完成</Tag>;
      default:
        return null;
    }
  };

  const getCurrentStep = () => {
    if (!order) return 0;
    
    switch (order.status) {
      case 'pending':
        return 1;
      case 'paid':
        return 2;
      case 'completed':
        return 3;
      case 'cancelled':
        return 0;
      default:
        return 0;
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px 0' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!order) {
    return <div>订单不存在</div>;
  }

  return (
    <div className="order-detail-page">
      <Breadcrumb style={{ marginBottom: 16 }}>
        <Breadcrumb.Item>
          <Link to="/">
            <HomeOutlined /> 首页
          </Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <Link to="/orders">我的订单</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>订单详情</Breadcrumb.Item>
      </Breadcrumb>
      
      <Card style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <Title level={3}>订单详情 {getStatusTag(order.status)}</Title>
          <div>
            {order.status === 'pending' && (
              <>
                <Button 
                  type="primary" 
                  onClick={handlePay} 
                  loading={paying}
                  style={{ marginRight: 8 }}
                >
                  立即支付
                </Button>
                <Button 
                  danger 
                  onClick={handleCancel} 
                  loading={cancelling}
                >
                  取消订单
                </Button>
              </>
            )}
          </div>
        </div>
        
        <Steps current={getCurrentStep()} status={order.status === 'cancelled' ? 'error' : 'process'}>
          <Step title="下单" icon={<ShoppingOutlined />} description={formatDate(order.createdAt)} />
          <Step title="支付" icon={<CreditCardOutlined />} description={order.status === 'pending' ? '待支付' : formatDate(order.updatedAt)} />
          <Step title="完成" icon={<CheckCircleOutlined />} description={order.status === 'completed' ? formatDate(order.updatedAt) : '处理中'} />
        </Steps>
      </Card>
      
      <Card title="订单信息" style={{ marginBottom: 24 }}>
        <Descriptions bordered column={1}>
          <Descriptions.Item label="订单编号">{order.orderNumber}</Descriptions.Item>
          <Descriptions.Item label="订单状态">{getStatusTag(order.status)}</Descriptions.Item>
          <Descriptions.Item label="创建时间">{formatDate(order.createdAt)}</Descriptions.Item>
          {order.status !== 'pending' && (
            <Descriptions.Item label="支付时间">{formatDate(order.updatedAt)}</Descriptions.Item>
          )}
          <Descriptions.Item label="支付方式">{order.paymentMethod || '未支付'}</Descriptions.Item>
          <Descriptions.Item label="订单金额">¥{order.totalAmount.toFixed(2)}</Descriptions.Item>
        </Descriptions>
      </Card>
      
      <Card title="商品信息">
        <List
          itemLayout="horizontal"
          dataSource={order.items}
          renderItem={item => (
            <List.Item>
              <Row style={{ width: '100%' }} gutter={16} align="middle">
                <Col xs={8} md={4}>
                  <Image 
                    src={item.product.imageUrl} 
                    alt={item.product.name}
                    style={{ width: '100%', maxHeight: 100, objectFit: 'contain' }}
                  />
                </Col>
                <Col xs={16} md={12}>
                  <Link to={`/products/${item.product.id}`}>
                    <Text strong>{item.product.name}</Text>
                  </Link>
                </Col>
                <Col xs={12} md={4} style={{ textAlign: 'center' }}>
                  <Text>¥{item.price.toFixed(2)}</Text>
                </Col>
                <Col xs={12} md={4} style={{ textAlign: 'center' }}>
                  <Text>x{item.quantity}</Text>
                </Col>
              </Row>
            </List.Item>
          )}
        />
        
        <Divider />
        
        <div style={{ textAlign: 'right' }}>
          <Text style={{ marginRight: 8 }}>共 {order.items.length} 件商品</Text>
          <Text strong style={{ fontSize: 16 }}>
            合计: <span style={{ color: '#f50' }}>¥{order.totalAmount.toFixed(2)}</span>
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default OrderDetailPage; 